package mybatis.service.impl;

import java.util.List;

import com.github.pagehelper.PageHelper;
import mybatis.dao.AddressDao;
import mybatis.dao.CartDao;
import mybatis.dao.OrderDao;
import mybatis.dao.OrderItemDao;
import mybatis.entity.Address;
import mybatis.entity.Cart;
import mybatis.entity.Order;
import mybatis.entity.OrderItem;
import mybatis.service.OrderService;
import mybatis.util.DBUtils;
import mybatis.util.RandomId;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements OrderService {
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private AddressDao addressDao;
	@Autowired
	private CartDao cartDao;
	@Autowired
	private OrderItemDao orderItemDao;

	@Override
	public String submit(Order order, int addrId) {
		// TODO Auto-generated method stub

		String orderNumber = RandomId.RandomId(order.getUser().getId());
		order.setOrder_number(orderNumber);
		Address addr = addressDao.findByAid(addrId);
		System.out.println("地址是"+addr);
		System.out.println();
		order.setUseraddress(addr);
		List<Cart> carts = order.getGamecount();
		for(Cart c : carts) {
			OrderItem item = new OrderItem();
			item.setOldprice(c.getGame().getGame_original_price());
			item.setFinalprice(c.getGame().getGame_final_price());
			item.setGamecount(c.getGamecount());
			item.setGid(c.getGid());
			item.setUserid(c.getUserid());
			item.setOrdernumber(orderNumber);
			orderItemDao.add(item);
			cartDao.removeByCid(c.getId());
		}
		orderDao.add(order);
		return orderNumber;
	}

	
	   /**
     * 生成订单号（25位）：时间（精确到毫秒）+3位随机数+5位用户id
     */


	@Override
	public Order findByOnumber(String number) {
		// TODO Auto-generated method stub
		Order order = orderDao.findByOnumber(number);
		int count  = order.getList().size();
		order.setCount(count);
		return order;
	}

	@Override
	public List<Order> findByUid(int Userid) {
		List<Order> order = orderDao.findByUid(Userid);
		return order;
	}


	@Override
	public List<Order> findPageByUid(int Userid,int currentPage) {
		PageHelper.startPage(currentPage,10,true);
		List<Order> list = orderDao.findByUid(Userid);
		return list;
	}
	


}
